package com.beyondbit.demo.controller;

import com.beyondbit.web.infrastructure.model.JsonResultMessage;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import lombok.var;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

/**
 *  api通用错误处理
 * @Author: lvfahai
 * @Date: 2020/3/11 18:25
 */
@Slf4j
@ControllerAdvice
@RestController
public class ErrorResponseExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler(Exception.class)
    public final ResponseEntity<JsonResultMessage> handleUnhandledException(Exception ex, WebRequest request) {
        var message = ex.getMessage();
        val cause = ex.toString();

        if (StringUtils.isBlank(message)) {
            message = cause;
        }

        val result = JsonResultMessage.createFailure(message);
        result.setCause(cause);
        log.error(cause);

        return new ResponseEntity<>(result, HttpStatus.OK);
    }
}
